package com.jeesite.modules.util;

import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.commons.lang3.StringUtils;

import sun.font.FontDesignMetrics;

import com.jeesite.modules.config.Contacts;
import com.jeesite.modules.goods.entity.ZtGoods;
import com.jeesite.modules.xcxAdmin.entity.ZtAdmin;


/**
 * 把两张图片合并
 * @version 2018-2-27 上午11:12:09
 *
 */
public class Picture1
{
     private Graphics2D g        = null;  
      
    /**  
     * 导入本地图片到缓冲区  
     */  
    public BufferedImage loadImageLocal(String imgName) {  
        try {  
            return ImageIO.read(new File(imgName));  
        } catch (IOException e) {  
            System.out.println(e.getMessage());  
        }  
        return null;  
    } 
    
	public BufferedImage loadImageLocal_head(String url){
		BufferedImage resultImg = null;
		try {
			if (StringUtils.isBlank(url)) {
				return null;
			}
			BufferedImage buffImg1 = ImageIO.read(new URL(url));
			resultImg = new BufferedImage(buffImg1.getWidth(), buffImg1.getHeight(), BufferedImage.TYPE_INT_RGB);
			Graphics2D g = resultImg.createGraphics();
			Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, buffImg1.getWidth(), buffImg1.getHeight());
			// 使用 setRenderingHint 设置抗锯齿
			g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
			resultImg = g.getDeviceConfiguration().createCompatibleImage(buffImg1.getWidth(), buffImg1.getHeight(),
					Transparency.TRANSLUCENT);
			//g.fill(new Rectangle(buffImg2.getWidth(), buffImg2.getHeight()));
			g = resultImg.createGraphics();
			  
		            g.setColor(Color.WHITE);
		            g.setStroke(new BasicStroke(2));
		            
		        
			// 使用 setRenderingHint 设置抗锯齿
			g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
			g.setClip(shape);
			g.drawImage(buffImg1, 0, 0, null);
			g.dispose();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return resultImg;
	}

    
    
    /**
     * 头像
     * @param b
     * @param d
     * @return
     */
    public BufferedImage modifyImagetogeter_hc(BufferedImage b, BufferedImage d) {  
        
        try {  
            int w = d.getWidth();  
            int h = d.getHeight();  
 
     
            g = d.createGraphics();  //1070
            g.drawImage(b, w-130, 200, w-260, w-260, null);  //商品图
            g.dispose();  
        } catch (Exception e) {  
            System.out.println(e.getMessage());  
        }  
  
        return d;  
    } 
    
    public static Map getWordWidth(Font font, String content) {
    	Map map=new HashMap();
        FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);
       int height= metrics.getHeight();
        int width = 0;
        for (int i = 0; i < content.length(); i++) {
            width += metrics.charWidth(content.charAt(i));
        }
        map.put("width",width);
        map.put("height",height);
        return map;
    }
    
 public BufferedImage modifyImagetogeter(BufferedImage b, ZtGoods ztGoods,String uname,String headimgurl) {  
	  Picture1 tt = new Picture1(); 
	
	  BufferedImage d = null;
	  try {
			d = ImageIO.read(new URL(Contacts.detailBackimg));
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} //背景
	
	  BufferedImage qcode=null;
	try {
		qcode = ImageIO.read(new URL(ztGoods.getQcode()));
	} catch (Exception e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
	  int w = d.getWidth();  
      int h = d.getHeight();  
      
	 try {  
         
         g = d.createGraphics();  //1070
         g.drawImage(b, w-295, h-378, 230, 230, null);  //二维码
         g.dispose();  
     } catch (Exception e) {  
         System.out.println(e.getMessage());  
     }  
	 
	 try {  
         
		 g = d.createGraphics();  //1070
         g.drawImage(qcode, 67, 130, w-134, w-134, null);  //商品图
         g.dispose();  
     } catch (Exception e) {  
       
     } 

     
       d= tt.modifyImage(d, uname,ztGoods.getTitle(),ztGoods.getRemarks(),ztGoods.getCommonPrice(),ztGoods.getDiscountPrice(),headimgurl);
        
      //  BufferedImage result= tt.modifyImagetogeter_hc(admin, d);
         return d;   
 
    } 
    
    //Microsoft YaHei
  //  private Font font = new Font("Microsoft YaHei", Font.PLAIN, 36);

    Font font = new Font("Microsoft YaHei", Font.PLAIN, 39); 
    
    private int x=0,y=0;
    /**
     * 修改图片,返回修改后的图片缓冲区（只输出一行文本）
     */
    public BufferedImage modifyImage(BufferedImage img, String username,String title,String subTitle,double price,double disPrice,String headimgurl) { 
    	int x=400,y=100;
    	Picture1 tt = new Picture1(); 
      try { 
        int w = img.getWidth(); 
       
        int h = img.getHeight(); 
        
        // 验证输出位置的纵坐标和横坐标 
        if (x >= h || y >= w) { 
          this.x = h - 40 + 2; 
          this.y = w; 
        } else { 
          this.x = x; 
          this.y = y; 
        } 
        if (username != null) { 
        	 Map m= getWordWidth(font, username);
        	BufferedImage admin = tt.loadImageLocal_head(headimgurl); 
             
             try {  
                 g = img.createGraphics();  
                 g.drawImage(admin, 75, h-315, 110, 110, null);  //掌柜头像
                 g.dispose();  
             } catch (Exception e) {  
                
             }  	
           
             g = img.createGraphics();  
            
            y=(200-Integer.valueOf(m.get("height").toString()))/2;
         
           
            if (this.font != null) 
              g.setFont(this.font);
            
         
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);//设置抗锯齿
            g.setPaint(new Color(0, 0, 0, 64));//阴影颜色
            
            g.drawString(username, 200, h-250);    //店铺

           g.setPaint(Color.BLACK);//正文颜色
          
           g.drawString(username, 200,h-250);    //店铺
         
        } 
      
        font = new Font("Microsoft YaHei", Font.PLAIN, 74);
        
    	  g.setFont(this.font); 
    	 
    	  g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);//设置抗锯齿
          g.setPaint(new Color(0, 0, 0, 64));//阴影颜色
    	  g.drawString("￥"+price, 75, w+81); 
    	  g.setPaint(new Color(255, 50, 100));
       
          g.drawString("￥"+price, 75, w+81); 
        
          
    	  int disWid= (int) getWordWidth(font, "￥"+price).get("width");
        
        font = new Font("Microsoft YaHei", Font.PLAIN, 41);
    	g.setFont(this.font); 
    	  g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);//设置抗锯齿
          g.setPaint(new Color(0, 0, 0, 64));//阴影颜色
          g.drawString("会员价：￥"+disPrice, 138+disWid, w+76); 
    	  g.setPaint(new Color(255, 50, 100));
    
    	 g.drawString("会员价：￥"+disPrice, 138+disWid, w+76); 
        
        
        if (title != null) { //110, 940
        	font = new Font("Microsoft YaHei", Font.PLAIN, 43);
        	g.setFont(this.font); 
        	
        	
        	/*g.setColor(Color.black);
            g.drawString(title.toString(), 80, h-470); */
            
        	int fontlen = (int) getWordWidth(font, title).get("width");

        	//文字叠加,自动换行叠加
        	int tempX = 80;
        	int tempY = h-472;
        	int tempCharLen = 0;//单字符长度
        	int tempLineLen = 0;//单行字符总长度临时计算
        	StringBuffer sb =new StringBuffer();
        	FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);
        	int j=0;
        	for(int i=0; i<title.length(); i++) {
        	char tempChar = title.charAt(i);
        	tempCharLen= metrics.charWidth(tempChar);

        	tempLineLen += tempCharLen;

        	if(tempLineLen >= (w-160)) {
        		j++;
        	//长度已经满一行,进行文字叠加
        		if(j==3){break;}
        		 g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);//设置抗锯齿
                 g.setPaint(new Color(0, 0, 0, 64));//阴影颜色
        		g.drawString(sb.toString(), tempX, tempY);
        		g.setPaint(Color.black);
        	g.drawString(sb.toString(), tempX, tempY);
        	
        	sb.delete(0, sb.length());//清空内容,重新追加

        	tempY += 57;

        	tempLineLen =0;
        	
        	}
        	sb.append(tempChar);//追加字符
        	}
  
          if(tempLineLen>0 && StringUtils.isNotBlank(sb.toString())&&j<2){
        	  g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);//设置抗锯齿
              g.setPaint(new Color(0, 0, 0, 64));//阴影颜色
              
        	  g.drawString(sb.toString(), tempX, tempY);
      			g.setPaint(Color.black);
        	  g.drawString(sb.toString(), tempX, tempY);
          }
        	
         } 
   /*     if (subTitle != null) { //110, 940
        	font = new Font("Microsoft YaHei", Font.PLAIN, 36);
        	g.setFont(this.font); 
        	
        	
         
        	int fontlen = (int) getWordWidth(font, subTitle).get("width");

        	//文字叠加,自动换行叠加
        	int tempX = 80;
        	int tempY = h-335;
        	int tempCharLen = 0;//单字符长度
        	int tempLineLen = 0;//单行字符总长度临时计算
        	StringBuffer sb =new StringBuffer();
        	FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);
        	int j=0;
        	for(int i=0; i<subTitle.length(); i++) {
        	char tempChar = subTitle.charAt(i);
        	tempCharLen= metrics.charWidth(tempChar);

        	tempLineLen += tempCharLen;

        	if(tempLineLen >= (w-550)) {
        		j++;
        	//长度已经满一行,进行文字叠加
        		if(j==4){break;}
        		 g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);//设置抗锯齿
                 g.setPaint(new Color(0, 0, 0, 64));//阴影颜色
        		g.drawString(sb.toString(), tempX, tempY);
        		g.setPaint(Color.GRAY);
        	g.drawString(sb.toString(), tempX, tempY);
        	
        	sb.delete(0, sb.length());//清空内容,重新追加

        	tempY += 52;

        	tempLineLen =0;
        	
        	}
        	sb.append(tempChar);//追加字符
        	}
  
          if(tempLineLen>0 && StringUtils.isNotBlank(sb.toString())&&j<3){
        	  g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);//设置抗锯齿
              g.setPaint(new Color(0, 0, 0, 64));//阴影颜色
        	  g.drawString(sb.toString(), tempX, tempY);
      		g.setPaint(Color.GRAY);
        	  g.drawString(sb.toString(), tempX, tempY);
          }
        	
         } */
        g.dispose(); 
      } catch (Exception e) { 
        System.out.println(e.getMessage()); 
      } 
     
      return img; 
    } 
    
    /**  
     * 生成新图片到本地  
     */  
    public void writeImageLocal(String newImage, BufferedImage img) {  
        if (newImage != null && img != null) {  
            try {  
                File outputfile = new File(newImage);  
                ImageIO.write(img, "jpg", outputfile);  
            } catch (IOException e) {  
                System.out.println(e.getMessage());  
            }  
        }  
    } 
        
  
    public BufferedImage loadImageLocal_head_01(String url){
    	        BufferedImage bi1=null;
				try {
					bi1 = ImageIO.read(new URL(url));
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    	 
    	        // 根据需要是否使用 BufferedImage.TYPE_INT_ARGB
    	        BufferedImage image = new BufferedImage(bi1.getWidth(), bi1.getHeight(),
    	                BufferedImage.TYPE_INT_RGB);
    	         
    	 
    	        Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, bi1.getWidth(), bi1
    	                .getHeight());
    	 
    	        Graphics2D g2 = image.createGraphics();
    	        image = g2.getDeviceConfiguration().createCompatibleImage(bi1.getWidth(), bi1.getHeight(), Transparency.TRANSLUCENT);
    	        g2 = image.createGraphics();
    	        g2.setBackground(Color.RED);
    	        g2.fill(new Rectangle(image.getWidth(), image.getHeight()));
    	        g2.setClip(shape);
    	        // 使用 setRenderingHint 设置抗锯齿
    	        g2.drawImage(bi1, 0, 0, null);
    	        g2.dispose();
    	 
    	       return image;
    	    }  
     
    public static void main(String[] args) {
    	BufferedImage bi1=null;
		try {
			bi1 = ImageIO.read(new URL("http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIRYXHlGLzuunjZBP9eSMibuHm4rM5ozwO9HterksgiaP5W377gKpiahLyExswWV6sd8wdszkj8NZMgw/132"));
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        
        // 根据需要是否使用 BufferedImage.TYPE_INT_ARGB
        BufferedImage image = new BufferedImage(bi1.getWidth(), bi1.getHeight(),
                BufferedImage.TYPE_INT_ARGB);
  
        Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, bi1.getWidth(), bi1
                .getHeight());
         
        Graphics2D g2 = image.createGraphics();
        image = g2.getDeviceConfiguration().createCompatibleImage(bi1.getWidth(), bi1.getHeight(), Transparency.TRANSLUCENT);
        g2 = image.createGraphics();
        g2.setComposite(AlphaComposite.Clear);
        g2.fill(new Rectangle(image.getWidth(), image.getHeight()));
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f));
        
        
     

        
        g2.setClip(shape);
        // 使用 setRenderingHint 设置抗锯齿
        g2.drawImage(bi1, 0, 0, null);
        
        g2.dispose();
         
        try {
            ImageIO.write(image, "PNG", new File("d:\\w2.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
}
